package com.appcaja.server.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.appcaja.server.dao.IOrdenDAO;
import com.appcaja.server.dao.OrdenRowMapper;
import com.appcaja.server.model.Orden;

@Repository
@SuppressWarnings("all")
public class OrdenSQLServerDao extends JdbcDaoSupport implements IOrdenDAO {

	@Autowired
	private DataSource dataSource;
 
	@PostConstruct
	private void initialize() {
		setDataSource(dataSource);
	}

	@Override
	public List<Orden> obtenerOrdenes() {
		List<Orden> ordenes = getJdbcTemplate().queryForList("select cgi, "
				+ "Expediente as nroExpediente, CausanteBeneficiario "
				+ "as causanteBeneficiario, estadoVerif, fechavenc from CajaJubilConsultaMobile");
		return ordenes;
	}

	@Override
	public Orden obtenerOrdenPorCGI(long cgi) {
		String query = "select cgi, Expediente, CausanteBeneficiario, estadoVerif, fechavenc "
				+ "from CajaJubilConsultaMobile where cgi = ?";
		Orden orden = null;
		List <Orden> ordenes = getJdbcTemplate().query(query, new Object[]{cgi}, new OrdenRowMapper());
		if (ordenes != null && !ordenes.isEmpty()) {
			orden = ordenes.get(0);
		}
		return orden;
	}
	
	@Override
	public List<Orden> filtrarOrdenes(Map<String, List<String>> filtros) {
		StringBuilder sb = new StringBuilder();
		sb.append("select cgi, Expediente, CausanteBeneficiario, estadoVerif, fechavenc ");
	    sb.append("from CajaJubilConsultaMobile ");
	    if(!filtros.isEmpty()){
	    	sb.append("where ");
	    	for (String filtro : filtros.keySet()) {
	    		if (filtro.equals("CausanteBeneficiario")) {
	    			sb.append(filtro);
	    			sb.append(" like :");
	    			sb.append(filtro);
	    			sb.append(" and ");
	    		} else if (filtro.equals("fechaDesde")) {
	    			sb.append("fechacarga");
	    			sb.append(" >= :");
	    			sb.append(filtro);
	    			sb.append(" and ");
	    		} else if (filtro.equals("fechaHasta")) {
	    			sb.append("fechacarga");
	    			sb.append(" <= :");
	    			sb.append(filtro);
	    			sb.append(" and ");
	    		} else {
		    		sb.append(filtro);
		    		sb.append(" in (:");
		    		sb.append(filtro);
		    		sb.append(") and ");
	    		}
	    	}
	    	sb.replace(sb.lastIndexOf("and"),sb.length(),"");
	    }
	    System.out.println("::QUERY LOG:: " + sb.toString());
	    NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());
	    List <Orden> ordenes = jdbcTemplate.query(sb.toString(), filtros, new OrdenRowMapper());
	    return ordenes;
	}

}
